package com.jayqqaa12.robot.lottery;

import java.util.List;
import java.util.Random;
import java.util.Set;

import weiboclient4j.StatusService;
import weiboclient4j.WeiboClientException;
import weiboclient4j.model.RepostTimeline;
import weiboclient4j.model.Status;
import weiboclient4j.model.User;
import weiboclient4j.params.P;
import weiboclient4j.params.Paging;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jayqqaa12.robot.model.Lottery;
import com.jayqqaa12.robot.model.Weibo;

/***
 * lottery
 * 
 * @author 12
 *
 *         http://weibo.com/1296023480/CBUFE2lpg?from=
 *         page_1005051296023480_profile
 *         &wvr=6&mod=weibotime&type=comment#_rnd1444375191897
 */
public class LotteryService {
	
	
	
	
	public  static Set<User> lottery(String id, boolean followMe, String sex, int count, String token, String uid) {


		StatusService service = new StatusService(SinaService.getClient(token));
		List<User> list = Lists.newArrayList();

		try {

			int i = 0;
			int total = 0;
			int c = 0;
			do {
				RepostTimeline tl = service.getRepostTimeline(P.id(id), Paging.create().count(200).page(++i));
				total = (tl.getTotalNumber() / 200) + 1;

				for (Status s : tl.getReposts()) {
					c++;
					User u = s.getUser();

					if (u.getFollowersCount() > 88 && (u.getFollowersCount()-10) > u.getFriendsCount()) {

						if (followMe && u.isFollowMe()) {
							if (sex != null && u.getGender().equals(sex))   add(list,u);
							else add(list,u);
						} else  add(list,u);

					}
				}

			} while (i < total);

			System.out.println("get ok user = " + list.size() + " get status c =" + c);

			Set<User> result = Sets.newHashSet();

			if (list.size() > 0) {

				while (--count >= 0) {
					
 
					User u = list.remove(new Random().nextInt(list.size()));
					result.add(u);
					
					
				}
			}
			
			// record result 
			if(result.size()>0){
				Weibo w=	new Weibo().set("sid", id).set("uid", uid);
				w.save();
				for(User u :result){
					new Lottery().set("sid", id).set("name", u.getName()).set("uid", u.getId()).save();
				}
				
			}
			
			

			return result;

		} catch (WeiboClientException e) {
			e.printStackTrace();
			return Sets.newHashSet();
		}

	}
	
	
	private static void add(List<User> list ,User u){
		
		for(User user:list){
			if(user.getId()==u.getId()) return ;
		}
		list.add(u);
	}
	

 

}
